<template>
  <main-card title="AI应用" :tabs="getTabs()" :main-body-style-obj="mainBodyStyleObj">
    <template #screen-space>
      <div class="flex grid-justify-between flex-items-center">
        <div class="h-60 flex" style="align-items: center" :class="[emptyFlag ? '' : 'empty-bottom']">
          <!-- 筛选栏 -->

          <a-cascader
            v-model:value="algorithmIdCascader"
            :options="algorithmldOptions"
            :allow-clear="false"
            style="width: 230px"
            class="mr-8"
            :dropdown-style="{ width: '230px', overflow: 'hidden' }"
            :field-names="{ label: 'name', value: 'id' }"
            @change="handleAlgorithmChange"
          />
          <a-select
            ref="select"
            v-model:value="pageForm.appId"
            placeholder="请选择"
            style="width: 140px"
            :options="appldOptions"
            :field-names="{ label: 'name', value: 'id' }"
          />
          <a-divider type="vertical" style="height: 20px" />
          <a-range-picker
            v-model:value="rangeValue"
            style="width: 216px; height: 36px"
            :allow-clear="false"
            value-format="YYYY-MM-DD"
            @change="onRangeChange"
          />
          <div class="fc ml-16">
            <sync-outlined style="width: 14px; height: 14px; color: rgba(17, 22, 31, 0.52)" />
            <span class="reset" @click="reset">重置</span>
          </div>

          <a-button class="ml-8" type="primary" @click="search">查询</a-button>

          <div class="tools-btn"></div>
        </div>

        <!-- 趋势/ip列表切换 -->
        <div class="display-btns">
          <div :class="['btn', active && 'active']" style="padding-left: 8px" @click="activeSwitch">
            <img class="logo" :src="active ? listCheckActive : listCheckDefult" />
          </div>
          <div :class="['btn', !active && 'active']" @click="activeSwitch">
            <img class="logo" :src="!active ? layoutActive : layoutDefault" />
          </div>
        </div>
      </div>
    </template>
    <div>
      <!-- 趋势 -->
      <trend-statistics v-if="!active" ref="trendStatisticsRef" />
      <!-- ip列表 -->
      <i-p-list v-if="active && showChild" ref="IPListRef" :page-form="pageForm" :sort-info="sortInfo" @tableChange="IPTableChange" />
    </div>
  </main-card>
</template>

<script lang="ts" setup>
  import { SyncOutlined } from '@ant-design/icons-vue'
  import dayjs from 'dayjs'
  import { storage } from 'g6-fn'
  import { dateFormat } from 'g6-fn'
  import { nextTick, onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import layoutActive from '@/assets/img/customer/layout-active.svg'
  import layoutDefault from '@/assets/img/customer/layout-default.svg'
  import listCheckActive from '@/assets/img/customer/list-check-active.svg'
  import listCheckDefult from '@/assets/img/customer/list-check-default.svg'
  import { callRecordsApi } from '@/services/api'

  import { getTabs } from '../utils'
  import IPList from './components/IP-list.vue'
  import trendStatistics from './components/trend-statistics.vue'
  const route = useRoute()
  const mainBodyStyleObj = ref({
    padding: '0'
  })

  // 是否有数据
  const emptyFlag = ref<boolean>(true)
  const isLoading = ref<boolean>(false)
  // 时间
  const FIFTH_DAY = 14 * 24 * 60 * 60 * 1000 // 15天的毫秒数
  const rangeValue = ref<any>([dayjs(Date.now() - FIFTH_DAY), dayjs(Date.now())])
  const pageForm = ref<Record<string, string | number | undefined | [string, string]>>({
    algorithmId: '',
    versionId: '',
    appId: '',
    callTimeStart: dateFormat(rangeValue.value[0], 'YYYY-MM-DD 00:00:00'),
    callTimeEnd: dateFormat(rangeValue.value[1], 'YYYY-MM-DD 23:59:59')
  })

  // 算法版本级联
  const algorithmIdCascader = ref<string[]>([''])
  const algorithmldOptions = ref<Record<string, any>[]>([{ name: '全部算法服务', id: '' }])
  const appldOptions = ref<Record<string, string | number>[]>([{ name: '全部应用', id: '' }])

  // 获取算法、版本号级联
  const getAlVersionList = async (): Promise<void> => {
    // 获取算法
    const { data } = await callRecordsApi.getAlVersionList()
    algorithmldOptions.value = [
      ...algorithmldOptions.value,
      ...data.map((item: any) => ({ name: item.name, id: item.id, children: item.childList }))
    ]
  }

  // 获取应用列表
  const getAppList = async (): Promise<void> => {
    // 获取算法
    const { data } = await callRecordsApi.getAppList()
    appldOptions.value = [...appldOptions.value, ...data.map((item: any) => ({ name: item.name, id: item.id }))]
  }

  /**
   * 模块切换
   */
  const trendStatisticsRef = ref() // 趋势组件
  const IPListRef = ref() // ip列表组件
  const active = ref<boolean>(true) // 按钮激活位
  const activeSwitch = (): void => {
    active.value = !active.value
    storage.set('appRecordActive', active.value)

    search()
  }
  const activeFlag = (): void => {
    if (route.path === '/ai-app/app-record') {
      const re = storage.get('appRecordActive') || false
      active.value = re
    }
  }
  activeFlag()
  /**
   * ------------------IP列表----------
   */
  const sortInfo = ref<Record<string, string>>()

  // 重置
  const showChild = ref<boolean>(true)
  const IPTableChange = (data: any) => {
    pageForm.value.columns = data.columns
    pageForm.value.order = data.order
  }
  /**
   * ------------------筛选区---------
   */

  // 查询
  const recordData = ref<Record<string, any>>({})
  // 时间处理
  const onRangeChange = (e: any) => {
    if (e) {
      pageForm.value.callTimeStart = dateFormat(e[0], 'YYYY-MM-DD 00:00:00')
      pageForm.value.callTimeEnd = dateFormat(e[1], 'YYYY-MM-DD 23:59:59')
    }
  }
  // 级联处理
  const handleAlgorithmChange = (e: any) => {
    if (e[0]) {
      pageForm.value.algorithmId = e[0]
      pageForm.value.versionId = e[1]
    } else {
      pageForm.value.algorithmId = ''
      pageForm.value.versionId = ''
    }
  }

  // 搜索数据
  const search = async () => {
    if (active.value) {
      // ip列表初始化
      showChild.value = true
      await nextTick()
      if (IPListRef.value) {
        IPListRef.value.getIPListData(pageForm.value)
      }
    } else {
      showChild.value = false
      initTrendStatistics()
    }
  }

  // 趋势组件初始化
  const initTrendStatistics = async (): Promise<void> => {
    isLoading.value = true
    const { data } = await callRecordsApi.queryCallRecords(pageForm.value as Record<string, string>)
    recordData.value = data
    trendStatisticsRef.value.trendInit(recordData.value)
    isLoading.value = false
  }

  // 重置
  const reset = (): void => {
    rangeValue.value = [dayjs(Date.now() - FIFTH_DAY), dayjs(Date.now())]
    pageForm.value = {
      algorithmId: '',
      versionId: '',
      appId: '',
      callTimeStart: dateFormat(rangeValue.value[0], 'YYYY-MM-DD 00:00:00'),
      callTimeEnd: dateFormat(rangeValue.value[1], 'YYYY-MM-DD 23:59:59')
    }
    algorithmIdCascader.value = ['']

    if (active.value) {
      showChild.value = false
      IPListRef?.value.reset()

      nextTick(() => {
        showChild.value = true
        if (IPListRef.value) {
          IPListRef?.value.getIPListData(pageForm.value)
        }
      })
    } else {
      initTrendStatistics()
    }
  }

  onMounted(async () => {
    getAlVersionList()
    getAppList()

    await search()
  })
</script>

<style lang="less" scoped>
  .display-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px;
    padding: 3px 2px 3px 3px;
    width: 68px;
    height: 36px;
    background: #fff;
    border: 1px solid rgba(217, 217, 219, 0.5);
    border-radius: 100px;

    /* Shadow/button */
    box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.04);

    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      padding-right: 8px;
      background: #fff;
      cursor: pointer;
    }

    .active {
      padding-right: 0 !important;
      padding-left: 0 !important;
      width: 30px;
      height: 30px;
      border-radius: 100px;

      /* Shadow/S */
      box-shadow: 0 1px 3px 0 rgba(37, 37, 45, 0.16);
    }
  }

  .empty-bottom {
    &::after {
      position: absolute;
      bottom: 0;
      left: 0;
      display: block;
      width: 100%;
      height: 1px; /* 下边框的高度 */
      background-color: @border1; /* 下边框的颜色 */
      content: '';
    }
  }

  .reset {
    margin: 0 8px;
    font-size: 14px;
    color: rgba(17, 22, 31, 0.52);
    cursor: pointer;
  }
</style>
